package com.tl.khadmin.service.impl;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import com.alibaba.druid.util.StringUtils;
import com.tl.khadmin.bean.*;
import com.tl.khadmin.mapper.ProductBrandMapper;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import com.tl.khadmin.bean.Product;
import com.tl.khadmin.bean.ProductImg;
import com.tl.khadmin.bean.ProductType;
import com.tl.khadmin.bean.Staff;
import com.tl.khadmin.bean.Supplier;

import com.tl.khadmin.bean.dto.ProductDetailDto;
import com.tl.khadmin.bean.dto.ProductListDto;
import com.tl.khadmin.bean.dto.ProductSelectListDto;
import com.tl.khadmin.mapper.ProductImgMapper;
import com.tl.khadmin.mapper.ProductMapper;
import com.tl.khadmin.mapper.ProductTypeMapper;
import com.tl.khadmin.page.Page;
import com.tl.khadmin.service.ProductIService;
import com.tl.khadmin.util.CommonUtil;
import com.tl.khadmin.util.Constant;

@Service
public class ProductServiceImpl implements ProductIService {

    private static Logger log = Logger.getLogger(ProductServiceImpl.class);
    @Resource
    private ProductMapper productMapper;
    @Resource
    private ProductImgMapper productImgMapper;
    @Resource
    private ProductBrandMapper productBrandMapper;
    @Resource
    private ProductTypeMapper productTypeMapper;

    @Override
    public Map<String, Object> queryProductById(Integer id) {
        Map<String, Object> result = new HashMap<>();
        ProductDetailDto product = productMapper.queryProductDetail(id);
        List<ProductImg> imgList = productImgMapper.queryByProductId(id, null);
        result.put("product", product);
        result.put("imglist", imgList);
        return result;
    }

    @Override
    public List<ProductSelectListDto> listProductSelect(HttpSession session, Map<String, Object> param) {
        Supplier supplier = (Supplier) session.getAttribute(Constant.USER_SUPPLIER);
        Object lastTypeObj = param.get("lastType");
        if (lastTypeObj != null) {
            String lastType = lastTypeObj.toString();
            param.put("lastType", "-" + lastType);
        }
        return productMapper.listProductSelect(param);
    }

    @Override
    public Page<ProductListDto> showProductByPage(HttpSession session, Integer pageNum,
                                                  Integer pageSize, Map<String, Object> params) {
        Supplier supplier = (Supplier) session.getAttribute(Constant.USER_SUPPLIER);
        Page<ProductListDto> page = new Page<ProductListDto>(pageNum, pageSize);
        params.put("page", page);
        List<ProductListDto> list = productMapper.showProductByPage(params);
        page.setResult(list);
        return page;
    }

    @Override
    public Map<String, Object> saveProduct(HttpSession session, ProductDetailDto product) {
        Map<String, Object> map = new HashMap<String, Object>();
        Supplier supplier = (Supplier) session.getAttribute(Constant.USER_SUPPLIER);
        product.setSupplierId(supplier.getId());
        product.setCreateTime(new Date());
        //生成规则，HLB + 条形码
        product.setCode("HLB" + product.getBarCode());
        if (productMapper.countByBarCode(product.getBarCode()) > 0) {
            map.put("result", "fail");
            map.put("message", "条形码已存在，请重新输入");
            return map;
        }
        String productType = product.getProductType();
        if(StringUtils.isEmpty(productType)) {
        	map.put("result", "fail");
            map.put("message", "商品分类不能为空");
            return map;
        }
        String[] types = productType.split("-");
        Integer productTypeId = Integer.parseInt(types[types.length-1]);
        product.setProductTypeId(productTypeId);
        Integer result = productMapper.insertSelective(product);
        Integer id = product.getId();
        //详情图
        List<String> detailImgPaths = product.getDetailImgPaths();
        for (String img : detailImgPaths) {
            ProductImg productImg = new ProductImg();
            productImg.setImgPath(img);
            productImg.setProductId(id);
            productImg.setType(ProductImg.VICE_IMG);
            int rowd = productImgMapper.insert(productImg);
            if (rowd != 1) {
                log.info("插入详情图失败");
            }
        }

        //主图
        List<String> mainImgPaths = product.getMainImgPaths();
        for (String img : mainImgPaths) {
            ProductImg productImg = new ProductImg();
            productImg.setImgPath(img);
            productImg.setProductId(id);
            productImg.setType(ProductImg.MAIL_IMG);
            int rowm = productImgMapper.insert(productImg);
            if (rowm != 1) {
                log.info("插入主图失败");
            }
        }

        if (1 == result) {
            map.put("result", "success");
            map.put("message", id);
            return map;
        } else {
            map.put("result", "fail");
            return map;
        }
    }


    @Override
    public int updateShelveState(Integer id, Integer shelveState) {
        Product product = new Product();
        product.setId(id);
        product.setShelveState(shelveState.shortValue());
        return productMapper.updateByPrimaryKeySelective(product);
    }

    @Override
    public String saveProductImg(ProductImg productImg) {
        Integer ret = productImgMapper.insert(productImg);
        return CommonUtil.result(ret);
    }

    public Map<String, Object> saveProductPic(String basePath, MultipartFile[] files) {
        Map<String, Object> ret = new HashMap<String, Object>();
        if (files == null && files.length > 0) {
            ret.put("result", "fail");
            return ret;
        }
        try {
            DateFormat df = new SimpleDateFormat("yyyyMMddhhmmssSSS");
            File imgDir = new File(basePath);
            if (!imgDir.exists()) {
                imgDir.mkdirs();
            }
            List<String> picPath = new ArrayList<String>();
            for (MultipartFile file : files) {
                if (file != null && !file.isEmpty()) {
                    String datePath = df.format(new Date());
                    String picurl = datePath + ".jpg";
                    File toFile = new File(basePath, picurl);
                    file.transferTo(toFile);
                    picPath.add("/upload/productimg/" + picurl);
                }
            }
            ret.put("result", "success");
            ret.put("message", picPath);
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
            ret.put("reulst", "fail");
            return ret;
        }
    }

    @Override
    public String deleteProductById(Integer id) {
        if (id == null) {
            return CommonUtil.returnMapResultToJson("fail", "参数错误");
        }
        try {
            if (productMapper.deleteByPrimaryKey(id) == 1) {
                return CommonUtil.returnMapResultToJson("success", "删除成功");
            }
        } catch (Exception e) {
            return CommonUtil.returnMapResultToJson("fail", "数据不能被删除");
        }
        return CommonUtil.returnMapResultToJson("fail", "删除失败");
    }

    @Override
    public String updateProduct(HttpSession session, Product product) {
        Supplier supplier = (Supplier) session.getAttribute(Constant.USER_SUPPLIER);
        Product old = productMapper.selectByPrimaryKey(product.getId());
        //禁止供应商修改审核后的数据
        if (old.getAuditState().intValue() == 2 && supplier.getIsInterior() == 0) {
            return CommonUtil.returnMapResultToJson("fail", "不能修改审核后的数据");
        }
        try {
            int row = productMapper.updateByPrimaryKeySelective(product);
            return CommonUtil.returnMapResultByRows(row, "保存成功", "保存失败");
        } catch (Exception e) {
            e.printStackTrace();
            return CommonUtil.returnMapResultToJson("fail", "保存异常");
        }
    }

    @Override
    public String SyncHaoLiBeiProduct(HaoLiBeiGoods haoLiBeiGood) {
        Product product_old = productMapper.selectByBarCode(haoLiBeiGood.getBarcode());
        ProductDetailDto product = new ProductDetailDto();
        if (haoLiBeiGood.getCatId() > 0) {
            int catId = productTypeMapper.queryByHaoLiBeiParentId(haoLiBeiGood.getCatId());
            if (catId == 0) {
                return "1001 has_no_Cat";
            } else {
                String type = getTypeInfo(catId, "", "");
                String[] typeArr = type.split("@");
                String typeIdList = typeArr[1];
                String typeNameList = typeArr[0];
                product.setProductTypeId(catId);
                product.setProductType(typeIdList);
                product.setProductTypeName(typeNameList);
            }
        }


        if (haoLiBeiGood.getBrand() != null && !haoLiBeiGood.getBrand().isEmpty()) {
            int brandId = getBrandId(haoLiBeiGood.getBrand());
            product.setBrandId(brandId);
        } else {
            int brandId = getBrandId("");
            product.setBrandId(brandId);
        }
        product.setProductName(haoLiBeiGood.getName());
        product.setSubtitle(haoLiBeiGood.getName());
        product.setBarCode(haoLiBeiGood.getBarcode());
        product.setCode(haoLiBeiGood.getBn());
        product.setCreateTime(new Date());
        product.setIsDelete((short) 0);
        product.setDataSource((short) 1);
        product.setTradeType((short) 1);
        product.setMarketPrice((double) haoLiBeiGood.getPrice());
        product.setMakeCountry(haoLiBeiGood.getCountry());
        product.setShelfLife(0);
        product.setPackType(haoLiBeiGood.getUnit());
        product.setHotIndex(0);
        product.setShelveState((short) 1);
        product.setAuditState((short) 2);
//		if(haoLiBeiGood.isMarketable()){
//			product.setAuditState((short)1);
//			product.setShelveState((short)1); 
//		}
//		else {
//			product.setAuditState((short)0);
//			product.setShelveState((short)0); 
//		}

        if (product_old != null && product_old.getId() > 0) {
            if(product_old.getCode().equals(product.getCode())) {
                product_old.setProductTypeId(product.getProductTypeId());
                product_old.setBrandId(product.getBrandId());
                product_old.setProductName(product.getProductName());
                product_old.setProductType(product.getProductType());
                product_old.setProductTypeName(product.getProductTypeName());
                product_old.setMarketPrice(product.getMarketPrice());
                product_old.setMakeCountry(product.getMakeCountry());
                product_old.setBarCode(product.getBarCode());
                productMapper.updateByPrimaryKeySelective(product_old);
            }
        } else {
            productMapper.insertSelective(product);
        }


        return "1000";
    }

    private int getBrandId(String bandname) {
        int brandId = productBrandMapper.queryIdByBrandName(bandname);
        if (brandId > 0) {
            return brandId;
        } else {
            ProductBrand brand = new ProductBrand();
            brand.setCreateTime(new Date());
            brand.setBrandName(bandname);
            brand.setAlias(bandname);
            productBrandMapper.insertSelective(brand);
            int bId = productBrandMapper.queryIdByBrandName(bandname);
            return bId;
        }
    }

    private String getTypeInfo(int id, String typeNameList, String typeIdList) {
        ProductType productType = productTypeMapper.selectByPrimaryKey(id);
        if (productType.getParentId() > 0) {
            if (typeNameList.isEmpty()) {
                typeNameList = productType.getTypeName();
            } else {
                typeNameList = String.format("%s-%s", productType.getTypeName(), typeNameList);
            }
            if (typeIdList.isEmpty()) {
                typeIdList = productType.getId().toString();
            } else {
                typeIdList = String.format("%s-%s", productType.getId(), typeIdList);
            }
            return getTypeInfo(productType.getParentId(), typeNameList, typeIdList);
        } else {
            if (typeNameList.isEmpty()) {
                typeNameList = productType.getTypeName();
            } else {
                typeNameList = String.format("%s-%s", productType.getTypeName(), typeNameList);
            }
            if (typeIdList.isEmpty()) {
                typeIdList = productType.getId().toString();
            } else {
                typeIdList = String.format("%s-%s", productType.getId(), typeIdList);
            }
            return String.format("%s@%s", typeNameList, typeIdList);
        }
    }
//	@Override
//	public List<ProductSelectListDto> listProductSelect(HttpSession sttps, Product productn) {
//		// TODO Auto-generated method stub
//		return null;
//	}

    @Override
    public String audit(HttpSession session, Product product) {
        Supplier supplier = (Supplier) session.getAttribute(Constant.USER_SUPPLIER);
        //非内部供应商账号不能审核
        if (supplier.getIsInterior() == 0) {
            return CommonUtil.returnMapResultToJson("fail", "账号无权限");
        }
        Product ore = new Product();
        Staff staff = (Staff) session.getAttribute(Constant.USER);
        ore.setAuditState(product.getAuditState());
        ore.setId(product.getId());
        ore.setAuditId(staff.getId());
        ore.setAuditTime(new Date());
        int result = productMapper.updateByPrimaryKeySelective(ore);
        return CommonUtil.returnMapResultByRows(result, "提交成功", "提交失败，请重试");
    }

    @Override
    public String deleteProductByIds(String _ids) {
        String[] ids = _ids.substring(0, _ids.length() - 1).split(",");
        try {
            int result = productMapper.deleteProductByIds(ids);
            if (result > 0) {
                return CommonUtil.returnMapResultToJson("success", "删除成功");
            } else {
                return CommonUtil.returnMapResultToJson("fail", "删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return CommonUtil.returnMapResultToJson("fail", "删除异常");
        }
    }

}
